import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/model/tender_entity.dart';
import 'package:tender_flutter/page/track/api/api_track.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

import 'item/track_dynamic_cell.dart';

class TrackDynamicPage extends StatefulWidget {
  final String companyKey;
  final String companyName;

  const TrackDynamicPage({Key key, this.companyKey, this.companyName})
      : super(key: key);

  @override
  _TrackDynamicPageState createState() => _TrackDynamicPageState();
}

class _TrackDynamicPageState extends State<TrackDynamicPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<TenderEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  List<TenderList> _dataLists = [];

  /// 手动刷新数据
  void _manualRefersh() {
    if (_loadState == LoadState.State_Success && _refreshController != null) {
      _refreshController.requestRefresh();
    } else {
      _onRefresh();
    }
  }

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 企业标讯信息
  Future<ApiResponse<TenderEntity>> _getData() async {
    return await ApiTrack.getTrackCompanyTenderList<TenderEntity>(
        companyName: widget.companyName, page: page, pageCount: pageCount);
  }

  /// 对外投资
  FutureBuilder<ApiResponse<TenderEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TenderEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            TenderEntity entity = snapshot.data.result;
            if (snapshot.hasData) {
              List temps = entity.xList == null ? [] : entity.xList;
              if (snapshot.data.status == Status.SUCCESS) {
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted(resetFooterState: true);
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            emptyStr: _loadState == LoadState.State_Empty ? "未找到相关招投标记录" : null,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text(widget.companyName ?? "-", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initList() {
    return Column(children: [
      Expanded(
          child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: true,
              enablePullDown: false,
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: ListView.separated(
                itemCount: _dataLists.length,
                physics: const BouncingScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  TenderList model = _dataLists[index];
                  return TrackDynamicListCell(
                      data: model,
                      onTap: () {
                        LRouter.navigatorCtx(context).push(
                            Routes.tenderDetailPage,
                            queryParams: {"tenderId": model.id.toString()});
                      });
                },
                separatorBuilder: (BuildContext context, int index) {
                  return Divider(
                    height: ScreenAdapter.height(10),
                    color: ThemeColors.colorType11,
                  );
                },
              ))),
      InkWell(
          onTap: () {
            LRouter.navigatorCtx(context).push(Routes.companyDetailPage,
                arguments: CompanyDetailPageArguments(
                    companyKey: widget.companyKey,
                    companyName: widget.companyName));
          },
          child: Container(
            height: ScreenAdapter.height(100),
            color: ThemeColors.colorType6,
            alignment: Alignment.center,
            child: Text(
              "企业详情",
              style: TextStyle(
                  color: ThemeColors.colorWhite,
                  fontSize: ScreenAdapter.sp(32),
                  fontWeight: FontWeight.w500),
            ),
          ))
    ]);
  }
}
